<?php

namespace Validator;

class Validator {
	
        private $errorNumber = null;
        private static $instance;
       
        const WRONG_USERNAME_FORMAT = "Username has to be at least 5 characters and can only contain letters and numbers";
        const WRONG_PASSWORD_FORMAT = "Password to short";
        const WRONG_PASSWORD_MATCH = "Passwords do not match";
		const WRONG_EMPTY = "Field can not be blank";
		const WRONG_RATING_FORMAT = "Rating should be a number between 1-10";
		const WRONG_FILE_FORMAT = "Only jpeg, gif or png images allowed";
		const WRONG_SIZE = "Image must be less than 500kb";
		
        public static function GetInstance() {
            if (!self::$instance) {
                self::$instance = new Validator();
            }
            return  self::$instance;
        }
       
        public function GetValidationError() {
            return "<p class=message>".$this->errorNumber."</p>";
        }
		
		public function ValidateUsername($username) {
                if (preg_match('/^[a-zA-Z0-9]{5,}$/', $username)) {
                
                        return true;
                } else {
                        $this->errorNumber = self::WRONG_USERNAME_FORMAT;
                        return false;
                }
        }
 
        public function ValidatePassword($password, $password2) {
                if (strlen($password)>6){
                	if ($password == $password2) {
                                return true;
                        }
					else {
                        $this->errorNumber = self::WRONG_PASSWORD_MATCH;
                        return false;
                	}
                    
                } else {
                        $this->errorNumber = self::WRONG_PASSWORD_FORMAT;
                        return false;
                }
        }
		
		public function ValidateNotEmpty($field) {
			
			if (empty($field)) {
				 $this->errorNumber = self::WRONG_EMPTY;
                 return false;
			}
			return true;
		}
		
		public function ValidateRating($rating) {
			 if (($rating >=1 && $rating <=10)) {
			 	return true;
			 } else {
			 	$this->errorNumber = self::WRONG_RATING_FORMAT;
			 }
			
		}
		
		public function ValidateUpload() {
			if (isset($_FILES['upload'])) {
				$valid = array ('image/jpeg', 'image/jpg', 'image/gif', 'image/png' , 'image/x-png');
				if ($_FILES['upload']['size'] < 500000 ) {
					if (in_array($_FILES['upload']['type'], $valid )) {
						if (move_uploaded_file($_FILES['upload']['tmp_name'], "images/{$_FILES['upload']['name']}"))  { 
						$image = "{$_FILES['upload']['name']}";
						
						} 
					} else {
				 		$this->errorNumber = self::WRONG_FILE_FORMAT;
						return false;
				 		}
				}else{
					$this->errorNumber = self::WRONG_SIZE;
					return false;
				}
				
			}
			return $image;
		}

}